package com.EM1.www.servlet;

import com.EM1.www.dao.ConnectPaper;
import com.EM1.www.dao.ConnectQuestion;
import com.EM1.www.po.Paper;
import com.EM1.www.po.Question;
import com.EM1.www.po.Teacher;
import com.EM1.www.util.Arrayparse;
import com.EM1.www.util.UpdateSession;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;

@WebServlet("/Addquestions")
public class Addquesions extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String[] questionids = request.getParameterValues("questionid");
        ArrayList<Integer> questionid = Arrayparse.intparse(questionids);
        HttpSession session = request.getSession();
        Paper paper = (Paper) session.getAttribute("paper");
        for (Integer idi : questionid) {
            for (Integer idj : paper.getQuestionId()) {
                if(idi.intValue()==idj.intValue()){
                    questionid.remove(idi);
                }
            }
        }
        ConnectPaper connectPaper=new ConnectPaper();
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        try {
            connectPaper.insertpaper(teacher.getId(),paper.getTitle(),questionid);
            UpdateSession.updatePaper(request);
            Paper newpaper = connectPaper.selectnewPaper(paper);
            session.setAttribute("paper",newpaper);
            ConnectQuestion connectQuestion=new ConnectQuestion();
            ArrayList<Question> questions = connectQuestion.selectQuestion(questionid);
            request.setAttribute("questions",questions);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
